package com.one.listener;

import com.alibaba.fastjson.JSON;
import com.one.bean.CollectFootpoint;
import com.one.constant.RedisPrefixConstant;
import com.one.constant.SystemConstant;
import com.one.service.CollectFootpointService;
import com.one.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 监听所有db的过期事件__keyevent@*__:expired"
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private CollectFootpointService collectFootpointService;
    @Autowired
    private RedisUtils redisUtils;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理  监听用户收藏信息
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的 key，进行业务处理
        log.info("------ 获取到失效的 key:[{}]，进行业务处理 ------",message.toString());
        String expiredKey = message.toString();
        // redis中用户收藏记录状态失效  同步数据到mysql中
        if (expiredKey.contains(RedisPrefixConstant.USER_COLLECT_PREFIX)) {
            // 获取失效状态的用户收藏的key
            String key = expiredKey.replaceAll("STATUS", "");
            log.info("------ 用户收藏key [{}] ------", key);
            // redis中没有数据，说明用户已经取消收藏 拿到用户id和商品id 将其在数据库中记录删除
            if (!redisUtils.hasKey(key)) {
                String user_product = key.replaceAll(RedisPrefixConstant.USER_COLLECT_PREFIX, "");
                log.info("------ 用户收藏user_product [{}] ------", user_product);
                String userId = user_product.split(":")[0];
                String productId = user_product.split(":")[1];
                // 删除数据库中数据
                collectFootpointService.deleteCollectProduct(userId, productId);
            } else {
                //通过key获取对象
                CollectFootpoint collectFootpoint = JSON.parseObject(redisUtils.get(key).toString(), CollectFootpoint.class);
                collectFootpointService.collectProductToMysql(collectFootpoint.setUpdateDate(new Date()));
            }
        }
    }
}